package com.wanlian.router.net.internal;
import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by yuh on 2017/11/29.
 * SIMPLY BECAUSE YOU WANT TO BELIEVE IT
 */

public class DownLoadTask extends AsyncTask<String, Integer, File> {

    private Context mContext;

    private String fileName;
    private DownloadFileTaskFinishListener mDownFileTaskFinishListener;

    public DownLoadTask(Context context) {
        mContext = context;
    }

    public void startDownload(FileInfo info, DownloadFileTaskFinishListener listener) {
        if (info == null || !info.isValidInfo()) {
            throw new IllegalArgumentException("参数 无效");
        }
        mDownFileTaskFinishListener = listener;
        fileName = info.fileName;
        execute(info.url);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    private String getApkPath() {
        File cache = mContext.getExternalCacheDir();
        if (cache == null) {
            return mContext.getCacheDir() + File.separator + "apks";
        }
        return cache.getAbsolutePath() + File.separator + "apks";
    }

    @Override
    protected File doInBackground(String... params) {

        String path = getApkPath();
        if (!new File(path).exists()) {
            File dir = new File(path);
            if (!dir.mkdirs()) {
                return null;
            }
        }
        File apkfile = new File(path, fileName);
        if (apkfile.exists()) {
            if (!apkfile.delete()) {
                return null;
            }
        }
        try {
            if (!apkfile.createNewFile()) {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

//
        Request request = new Request.Builder()
                .url(params[0])
                .build();

        FileOutputStream fos = null;
        InputStream is = null;
        try {
            Response response = new OkHttpClient().newCall(request).execute();
            if (!response.isSuccessful()) {
                return null;
            }
            long total = response.body().contentLength();
            is = response.body().byteStream();
            byte[] buff = new byte[1024 * 2];
            int len;
            long sum = 0;
            int lastProgress = -1;

            fos = new FileOutputStream(apkfile);
            while ((len = is.read(buff)) != -1) {
                fos.write(buff, 0, len);
                sum += len;

                int currentProgress = (int) (sum * 100 / total);
                if (lastProgress != currentProgress) {
                    lastProgress = currentProgress;
                    publishProgress(lastProgress);
                }

                System.out.println(lastProgress);
            }
            fos.flush();

            if (total == sum) {
                return apkfile;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {

                }
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        if (mDownFileTaskFinishListener != null) {
            mDownFileTaskFinishListener.onProgress(values[0]);
        }
    }

    @Override
    protected void onPostExecute(File f) {
        super.onPostExecute(f);

        if (mDownFileTaskFinishListener != null) {
            mDownFileTaskFinishListener.onDownloadFinished(f);
        }
    }

    public interface DownloadFileTaskFinishListener {
        void onProgress(int progress);

        void onDownloadFinished(File file);
    }

    public static class FileInfo {
        public String fileName;
        public String url;

        public FileInfo(String fileName, String url) {
            this.fileName = fileName;
            this.url = url;
        }

        public boolean isValidInfo() {
            return !TextUtils.isEmpty(fileName) && !TextUtils.isEmpty(url);
        }
    }
}